package com.gitee.lilongyang.shell.config;

import com.gitee.lilongyang.shell.ShellInfo;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SystemConfig {

    public static JSch jsch = new JSch();

    public static Session createSession(ShellInfo info) throws JSchException {
        Session session = jsch.getSession(info.getUsername(), info.getHost(), info.getPort());
        return session;
    }

    /**
     * 关闭 session
     * @param session
     * @throws JSchException
     */
    public static void disconnectSession(Session session) throws JSchException {
        session.disconnect();
    }

    public static ChannelShell createShell(Session session) throws JSchException {
        ChannelShell channelShell  = (ChannelShell) session.openChannel("shell");
        return channelShell;
    }

    public static ChannelSftp createSFTP(Session session) throws JSchException {
        ChannelSftp channel  = (ChannelSftp) session.openChannel("sftp");
        return channel;
    }

    /**
     * 复制一个新的
     * @param channel
     * @param <T>
     * @return
     * @throws JSchException
     */
    public static   <T extends Channel> T copyChannel(T channel) throws JSchException {
        if (channel instanceof ChannelShell){
            return (T) createShell(channel.getSession());
        }else if (channel instanceof ChannelSftp){
            return (T) createShell(channel.getSession());
        }else {
            //如果不在这个类型里面需要实现其他通道
            return (T)channel;
        }
    }

    public static void main(String[] args) throws JSchException {
        ChannelShell channelShell = SystemConfig.createShell(null);
        ChannelShell newa = SystemConfig.copyChannel(channelShell);
    }

}
